﻿using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace CoffeeTeaTrading.Core.Infrastructure.Utils
{
    public class XmlUtils<T> where T : class
    {
        public static String Serialize(T document)
        {
            string documentString = string.Empty;
            MemoryStream ms = null;
            StreamReader fStream = null;
            try
            {
                XmlSerializer xmlFormat = new XmlSerializer(typeof(T));
                ms = new MemoryStream();
                xmlFormat.Serialize(ms, document);
                fStream = new StreamReader(ms);
                var bytes = ms.ToArray();
                documentString = Encoding.UTF8.GetString(bytes);
            }
            finally
            {
                if (ms != null)
                    ms.Close();
                if (fStream != null)
                    fStream.Close();
            }
            return documentString;
        }

        public static T Deserialize(string documentString)
        {
            MemoryStream ms = null;
            T document = null;
            try
            {
                ms = new MemoryStream(Encoding.UTF8.GetBytes(documentString));
                XmlSerializer x = new XmlSerializer(typeof(T));
                document = (T)x.Deserialize(ms);
            }
            finally
            {
                if (ms != null)
                    ms.Close();
            }
            return document;
        }
    }
}
